﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;

namespace Alos.Common
{
    public static class Current
    {
        public static AuthUser User
        {
            get
            {
                return GetAuthUser();
            }
        }

        public static string GetSessionKey(AuthUser au)
        {
            try
            {
                return Common.DESEncrypt.Encrypt(au.id + "|" + au.dt + "|" + au.ip);
            }
            catch
            {
                return string.Empty;
            }
        }
        public static AuthUser GetAuthUser()
        {
            string sessionKey = string.IsNullOrWhiteSpace(HttpContext.Current.Request.Headers["SessionKey"]) ? HttpContext.Current.Request["sk"] : HttpContext.Current.Request.Headers["SessionKey"];
            try
            {
                if (!string.IsNullOrWhiteSpace(sessionKey))
                {
                    string sk = Common.DESEncrypt.Decrypt(sessionKey);
                    if (!string.IsNullOrWhiteSpace(sk))
                    {
                        var aus = sk.Split('|');
                        return new AuthUser()
                        {
                            id = int.Parse(aus[0]),
                            dt = int.Parse(aus[1]),
                            ip = aus[2]
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                Log.errorlog(ex);
            }
            return null;
        }
    }


    public class AuthUser
    {
        public int dt { get; set; }
        public int id { get; set; }
        public string ip { get; set; }
        [ScriptIgnore]
        public bool overdue
        {
            get
            {
                return ((DateTime.Now.DayOfYear) * 24 + DateTime.Now.Hour) - dt > 1 || HttpContext.Current.Request.UserHostAddress != ip;
            }
        }
    }
}
